package top.fyxxxx.downloader.Service;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.widget.RemoteViews;

import top.fyxxxx.downloader.Activities.MainActivity;
import top.fyxxxx.downloader.R;
import top.fyxxxx.downloader.utils.DownloadListener;
import top.fyxxxx.downloader.utils.DownloadTask;
import top.fyxxxx.downloader.utils.LocalSession;

/**
 * Created by Administrator on 2018/7/20.
 */

public class MyService extends Service {

    private RemoteViews remoteViews;
    private int NOTIFICATION_ID_CNT=1;
    private NotificationManager manager;
    private Notification myNotify;
    private int downloadnum=0;
    @Override
    public void onCreate() {
        super.onCreate();
        System.out.println("Service onCreate");

    }


    /**
     * 启动
     * 前台服务
     */
    private void startPlayback(int id,String filename) {
        String CHANNEL_ONE_ID = "1";
        String CHANNEL_ONE_NAME= "CHANNEL_ONE_ID";
        String CHANNEL_TWO_ID="2";
        String CHANEL_TWO_NAME="CHANNEL_TWO_NAME";
        NotificationChannel notificationChannel= null;
        //进行8.0的判断
        manager= (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            notificationChannel= new NotificationChannel(CHANNEL_ONE_ID,
                    CHANNEL_ONE_NAME, NotificationManager.IMPORTANCE_MIN);
            NotificationChannel notificationChannel1=new NotificationChannel(CHANNEL_TWO_ID,CHANEL_TWO_NAME
            ,NotificationManager.IMPORTANCE_HIGH);
            manager.createNotificationChannel(notificationChannel1);
            manager.createNotificationChannel(notificationChannel);
        }
        NOTIFICATION_ID_CNT++;
        Intent intent = new Intent(this, MainActivity.class);
        PendingIntent pi = PendingIntent.getActivity(this, 1, intent, 0);

        remoteViews = new RemoteViews(getPackageName(),R.layout.text);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setChannelId("1");
        builder.setContent(remoteViews);
        builder.setSmallIcon(R.mipmap.ic_launcher);
        builder.setContentIntent(pi);
        myNotify = builder.build();

        myNotify.flags |= Notification.FLAG_NO_CLEAR;
        System.out.println("start");
        startForeground(id, myNotify);//重点
        remoteViews.setTextViewText(R.id.taskname,filename);
        remoteViews.setProgressBar(R.id.pb,100,0,false);
    }
    public void failed(int id,String filename){
        Intent intent = new Intent(this, MainActivity.class);
        PendingIntent pi = PendingIntent.getActivity(this, 1, intent, 0);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setChannelId("2");
        builder.setSmallIcon(R.mipmap.ic_launcher);
        builder.setContentIntent(pi);
        builder.setContentText(filename+"下载失败");
        Notification t= builder.build();
        t.flags |= Notification.FLAG_NO_CLEAR;
        manager.notify(id, t);
        try{
            Thread.sleep(2000);

        }
        catch (Exception e){
            ;
        }
        System.out.println(id);
        manager.cancel(id);
    }
    public void finished(int id,String filename){
        Intent intent = new Intent(this, MainActivity.class);
        PendingIntent pi = PendingIntent.getActivity(this, 1, intent, 0);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setChannelId("2");
        builder.setSmallIcon(R.mipmap.ic_launcher);
        builder.setContentIntent(pi);
        builder.setContentText(filename+"下载完成");
        Notification t= builder.build();
        t.flags |= Notification.FLAG_NO_CLEAR;
        manager.notify(id, t);
        try{
            Thread.sleep(2000);

        }
        catch (Exception e){
            ;
        }
        System.out.println(id);
        manager.cancel(id);
    }

    @Override
    public boolean stopService(Intent name) {
        if (name.getBooleanExtra("stop", false)) {
            stop();
        }
        return super.stopService(name);

    }

    /**
     * 停止前台服务
     */
    public void stop() {
        //移到后台并移出Notification
        System.out.println("end");

        stopForeground(true);

    }
    public void setProcess(int process,int id){
        remoteViews.setProgressBar(R.id.pb,100,process,false);
        remoteViews.setTextViewText(R.id.tv,process+"%");
        manager.notify(id,myNotify);
        if(process>=100){
            //System.out.println(id);
            //myNotify.defaults=Notification.DEFAULT_LIGHTS|Notification.DEFAULT_SOUND;
            manager.cancel(id);
       }
    }

    /*public void download(){
        startPlayback();
        downloading=true;
        int process=0;
        while (process<100){
            System.out.println(process);
            try {
                Thread.sleep(300);
            }
            catch (Exception e){
                ;
            }
            setProcess(process);
            process=(int)(downloadTask.progress()*100);
        }
        downloading=false;
    }*/
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        final DownloadTask downloadTask = (DownloadTask) LocalSession.get(intent.getStringExtra("task"));
        System.out.println(downloadTask.url);
        downloadTask.addListener(new DownloadListener(){
            private int NOTIFICATION_ID;
            private String filename=downloadTask.filename();
            @Override
            public void start() {
                downloadnum++;
                System.out.println(NOTIFICATION_ID_CNT);
                NOTIFICATION_ID=NOTIFICATION_ID_CNT;
                startPlayback(NOTIFICATION_ID_CNT,filename);
            }

            @Override
            public void loading(long cur,long tot) {
                setProcess((int)(cur*100.0/tot),NOTIFICATION_ID);
            }

            @Override
            public void complete(String path) {
                finished(NOTIFICATION_ID,filename);
                System.out.println(NOTIFICATION_ID);
                downloadnum--;
                if(downloadnum==0)stopSelf();
            }

            @Override
            public void fail(int code, String message) {
                failed(NOTIFICATION_ID,filename);
                downloadnum--;
                if(downloadnum==0)stopSelf();
            }

            @Override
            public void pause() {
                setProcess(100,NOTIFICATION_ID);
                downloadnum--;
                if(downloadnum==0)stopSelf();
            }

            @Override
            public void loadfail(String message) {
                failed(NOTIFICATION_ID,filename);
                downloadnum--;
                if(downloadnum==0)stopSelf();
            }
        });
        downloadTask.start();
        //stopSelf();
        return START_REDELIVER_INTENT;
    }
    @Override
    public void onDestroy(){
        System.out.println("Destroy");
        super.onDestroy();
    }
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


}